<template>
  <div class="tinymce-editor">
    <editor
      v-if="show"
      v-model="value"
      :init="init"
      :disabled="disabled"
      @contextmenu.prevent="()=>{}"
    />
  </div>
</template>
<script>
import { uploadFile } from '@/api/tool/file'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/themes/silver'
import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/link' // 超链接插件
import 'tinymce/plugins/code' // 代码块插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/contextmenu' // 右键菜单插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/colorpicker' // 选择颜色插件
import 'tinymce/plugins/textcolor' // 文本颜色插件
import 'tinymce/plugins/fullscreen' // 全屏
import 'tinymce/plugins/help'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/toc'
import 'tinymce/plugins/codesample'
import 'tinymce/icons/default/icons.min.js'

export default {
  name: 'TinymceEditor',
  components: {
    Editor
  },
  props: {
    content: {
      type: String,
      default: ''
    },
    // 基本路径，默认为空根目录，如果你的项目发布后的地址为目录形式，
    // 即abc.com/tinymce，baseUrl需要配置成tinymce，不然发布后资源会找不到
    baseUrl: {
      type: String,
      default: '/'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: 300
    },
    plugins: {
      type: [String, Array],
      default: 'lists image media table wordcount code fullscreen help codesample toc insertdatetime  searchreplace  link charmap paste hr'
    },
    toolbar: {
      type: [String, Array],
      default: 'bold italic underline strikethrough blockquote|forecolor backcolor|formatselect |fontsizeselect  | alignleft aligncenter alignright alignjustify | outdent indent |codeformat blockformats| removeformat undo redo bullist numlist toc pastetext|codesample charmap  hr insertdatetime |lists image media table link unlink |code searchreplace fullscreen help'
    },
    menubar: {
      type: [String, Boolean],
      default: 'file edit insert view format table'
    }
  },
  data() {
    return {
      show: false,
      init: {
        language_url: 'tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        convert_urls: false,
        skin_url: 'tinymce/skins/ui/oxide',
        content_css: 'tinymce/skins/content/default/content.css',
        // skin_url: 'tinymce/skins/ui/oxide-dark', // 暗色系
        // content_css: 'tinymce/skins/content/dark/content.css', // 暗色系
        height: this.height,
        plugins: this.plugins,
        toolbar: this.toolbar,
        browser_spellcheck: true, // 拼写检查
        branding: false,
        statusbar: false, // 隐藏编辑器底部的状态栏
        elementpath: false, // 禁用下角的当前标签路径
        menubar: this.menubar,
        // menubar: false,
        paste_data_images: true, // 允许粘贴图像
        setup: (editor) => {
          editor.ui.registry.addButton("fillblank", {
            text: "填空",
            onAction: function() {
              editor.insertContent('(____)')
            }
          })
        },
        // images_upload_credentials: true,
        images_upload_handler: (blobInfo, success, failure) => {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          formData.append('path', 'editor')
          uploadFile(formData).then(response => {
            success(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download/${response.param}`)
          }).catch(() => {})
        },
        // 视频预览功能
        media_url_resolver: (data, resolve) => {
          try {
            // const videoUri = this.$store.state.app.server_api + data.url
            const embedHtml = `<p>
                  <span
                    class="mce-object mce-object-video"
                    data-mce-selected="1"
                    data-mce-object="video"
                    data-mce-p-width="100%"
                    data-mce-p-height="auto"
                    data-mce-p-controls="controls"
                    data-mce-p-controlslist="nodownload"
                    data-mce-p-allowfullscreen="true"
                    data-mce-p-src=${data.url} >
                    <video src=${data.url} controls="controls" width="100%" height="auto" controlslist="nodownload" />
                  </span>
                </p>`
            resolve({ html: embedHtml })
          } catch (e) {
            resolve({ html: '' })
          }
        },
        file_picker_callback: (callback, value, meta) => {
          // 模拟出一个input用于添加本地文件
          const input = document.createElement('input')
          input.setAttribute('type', 'file')
          input.click()
          const that = this
          input.onchange = function() {
            const file = this.files[0]
            const formData = new FormData()
            formData.append('file', file)
            formData.append('path', 'editor')
            that.upload(callback, formData, file)
          }
        },
        init_instance_callback: editor => {
          editor.on('paste', (evt) => {
            // 监听粘贴事件
            // this.onPaste(evt)
          })
        }
      },
      value: this.content
    }
  },
  watch: {
    content(newValue) {
      this.value = newValue
    },
    value(newValue) {
      this.$emit('input', newValue)
    }
  },
  mounted() {
    this.show = true
    tinymce.init({})
  },
  methods: {
    upload(callback, formData, file) {
      uploadFile(formData).then(response => {
        callback(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download/${response.param}`, { title: file.name })
      }).catch(() => {})
    },
    update(content) {
      tinymce.activeEditor.setContent(content)
    },
    // 清空内容
    clear() {
      this.value = ''
    },
    close() {
      this.show = false
    }
  }
}
</script>

<style>
.tox-tinymce-aux {
  z-index: 9999!important;
}
</style>
